#include "precomp.h"
#include "jconcurrentthreadengine.h"

/**
 *
 */
namespace JConcurrent {

// - class ThreadEngineBarrierData -

/**
 * @brief The ThreadEngineBarrierData class
 */
class ThreadEngineBarrierData
{
public:

    /**
     * @brief ThreadEngineBarrierData
     */
    ThreadEngineBarrierData()
        : count(0)
    {

    }

    // The thread count is maintained as an integer in the count atomic
    // variable. The count can be either positive or negative - a negative
    // count signals that a thread is waiting on the barrier.

    // BC note: inlined code from Qt < 4.6 will expect to find the QMutex
    // and QAtomicInt here. ### Qt 5: remove.
    QMutex mutex;
    QAtomicInt count;
    QSemaphore semaphore;
};

// - class ThreadEngineBarrier -

/**
 * @brief ThreadEngineBarrier::ThreadEngineBarrier
 */
ThreadEngineBarrier::ThreadEngineBarrier()
    : d(new ThreadEngineBarrierData())
{

}

/**
 * @brief ThreadEngineBarrier::~ThreadEngineBarrier
 */
ThreadEngineBarrier::~ThreadEngineBarrier()
{
    delete d;
}

/**
 * @brief ThreadEngineBarrier::acquire
 */
void ThreadEngineBarrier::acquire()
{
    forever {
        int localCount = int(d->count);
        if (localCount < 0) {
            if (d->count.testAndSetOrdered(localCount, localCount -1))
                return;
        } else {
            if (d->count.testAndSetOrdered(localCount, localCount + 1))
                return;
        }
    }
}

/**
 * @brief ThreadEngineBarrier::release
 * @return
 */
int ThreadEngineBarrier::release()
{
    forever {
        int localCount = int(d->count);
        if (localCount == -1) {
            if (d->count.testAndSetOrdered(-1, 0)) {
                d->semaphore.release();
                return 0;
            }
        } else if (localCount < 0) {
            if (d->count.testAndSetOrdered(localCount, localCount + 1))
                return qAbs(localCount + 1);
        } else {
            if (d->count.testAndSetOrdered(localCount, localCount - 1))
                return localCount - 1;
        }
    }
}

// Wait until all threads have been released

/**
 * @brief ThreadEngineBarrier::wait
 */
void ThreadEngineBarrier::wait()
{
    forever {
        int localCount = int(d->count);
        if (localCount == 0)
            return;

        Q_ASSERT(localCount > 0); // multiple waiters are not allowed.
        if (d->count.testAndSetOrdered(localCount, -localCount)) {
            d->semaphore.acquire();
            return;
        }
    }
}

/**
 * @brief ThreadEngineBarrier::currentCount
 * @return
 */
int ThreadEngineBarrier::currentCount()
{
    return int(d->count);
}

// releases a thread, unless this is the last thread.
// returns true if the thread was released.

/**
 * @brief ThreadEngineBarrier::releaseUnlessLast
 * @return
 */
bool ThreadEngineBarrier::releaseUnlessLast()
{
    forever {
        int localCount = int(d->count);
        if (qAbs(localCount) == 1) {
            return false;
        } else if (localCount < 0) {
            if (d->count.testAndSetOrdered(localCount, localCount + 1))
                return true;
        } else {
            if (d->count.testAndSetOrdered(localCount, localCount - 1))
                return true;
        }
    }
}

/**
 * @brief ThreadEngineBase::ThreadEngineBase
 */
ThreadEngineBase::ThreadEngineBase()
    : futureInterface(0), threadPool(QThreadPool::globalInstance())
{
    setAutoDelete(false);
}

/**
 * @brief ThreadEngineBase::~ThreadEngineBase
 */
ThreadEngineBase::~ThreadEngineBase() {}

/**
 * @brief ThreadEngineBase::startSingleThreaded
 */
void ThreadEngineBase::startSingleThreaded()
{
    start();
    while (threadFunction() != ThreadFinished) { }
    finish();
}

/**
 * @brief ThreadEngineBase::startBlocking
 */
void ThreadEngineBase::startBlocking()
{
    start();
    barrier.acquire();
    startThreads();

    bool throttled = false;
#ifndef QT_NO_EXCEPTIONS
    try {
#endif
        while (threadFunction() == ThrottleThread) {
            if (threadThrottleExit()) {
                throttled = true;
                break;
            }
        }
#ifndef QT_NO_EXCEPTIONS
    } catch (JConcurrent::Exception &e) {
        handleException(e);
    } catch (...) {
        handleException(JConcurrent::UnhandledException());
    }
#endif

    if (throttled == false) {
        barrier.release();
    }

    barrier.wait();
    finish();
    exceptionStore.throwPossibleException();
}

/**
 * @brief ThreadEngineBase::startThread
 */
void ThreadEngineBase::startThread()
{
    startThreadInternal();
}

/**
 * @brief ThreadEngineBase::acquireBarrierSemaphore
 */
void ThreadEngineBase::acquireBarrierSemaphore()
{
    barrier.acquire();
}

/**
 * @brief ThreadEngineBase::isCanceled
 * @return
 */
bool ThreadEngineBase::isCanceled()
{
    if (futureInterface)
        return futureInterface->isCanceled();
    else
        return false;
}

/**
 * @brief ThreadEngineBase::waitForResume
 */
void ThreadEngineBase::waitForResume()
{
    if (futureInterface)
        futureInterface->waitForResume();
}

/**
 * @brief ThreadEngineBase::isProgressReportingEnabled
 * @return
 */
bool ThreadEngineBase::isProgressReportingEnabled()
{
    // If we don't have a QFuture, there is no-one to report the progress to.
    return (futureInterface != 0);
}

/**
 * @brief ThreadEngineBase::setProgressValue
 * @param progress
 */
void ThreadEngineBase::setProgressValue(int progress)
{
    if (futureInterface)
        futureInterface->setProgressValue(progress);
}

/**
 * @brief ThreadEngineBase::setProgressRange
 * @param minimum
 * @param maximum
 */
void ThreadEngineBase::setProgressRange(int minimum, int maximum)
{
    if (futureInterface)
        futureInterface->setProgressRange(minimum, maximum);
}

/**
 * @brief ThreadEngineBase::startThreadInternal
 * @return
 */
bool ThreadEngineBase::startThreadInternal()
{
    if (this->isCanceled())
        return false;

    barrier.acquire();
    if (threadPool.tryStart(this) == false) {
        barrier.release();
        return false;
    }
    return true;
}

/**
 * @brief ThreadEngineBase::startThreads
 */
void ThreadEngineBase::startThreads()
{
    while (shouldStartThread() && startThreadInternal()) { }
}

/**
 * @brief ThreadEngineBase::threadExit
 */
void ThreadEngineBase::threadExit()
{
    const bool asynchronous = futureInterface != 0;
    const int lastThread = (barrier.release() == 0);

    if (lastThread && asynchronous)
        this->asynchronousFinish();
}

// Called by a worker thread that wants to be throttled. If the current number
// of running threads is larger than one the thread is allowed to exit and
// this function returns one.

/**
 * @brief ThreadEngineBase::threadThrottleExit
 * @return
 */
bool ThreadEngineBase::threadThrottleExit()
{
    return barrier.releaseUnlessLast();
}

/**
 * @brief ThreadEngineBase::run
 */
void ThreadEngineBase::run() // implements QRunnable.
{
    if (this->isCanceled()) {
        threadExit();
        return;
    }

    startThreads();

#ifndef QT_NO_EXCEPTIONS
    try {
#endif
        while (threadFunction() == ThrottleThread) {
            // threadFunction returning ThrottleThread means it that the user
            // struct wants to be throttled by making a worker thread exit.
            // Respect that request unless this is the only worker thread left
            // running, in which case it has to keep going.
            if (threadThrottleExit())
                return;
        }

#ifndef QT_NO_EXCEPTIONS
    } catch (JConcurrent::Exception &e) {
        handleException(e);
    } catch (...) {
        handleException(JConcurrent::UnhandledException());
    }
#endif
    threadExit();
}

#ifndef QT_NO_EXCEPTIONS

/**
 * @brief ThreadEngineBase::handleException
 * @param exception
 */
void ThreadEngineBase::handleException(const JConcurrent::Exception &exception)
{
    if (futureInterface)
        futureInterface->reportException(exception);
    else
        exceptionStore.setException(exception);
}
#endif

} // namepsace QtConcurrent
